import React from 'react';
import { api, xhrGet } from '@/services';
import { Col, Row, Select as SelectForm, Form } from 'antd';
import _ from 'lodash';
import { ExtBtn } from '@/components/SelfIcon';
import { ResponseType } from 'common-module';
import PropsComp from '../props-comp';
import './index.less';
import { getValidateMessage } from '@/utils/validate-rules/message';

const { Option } = SelectForm;
const DICT = ['dataOperatorOptions', 'braceOptions', 'logicOperatorOptions'];
interface Condition {
  opKey: 'DATA_OPRTR' | 'PARENTHESIS' | 'LOGCL_OPRTR' | 'ATRBT_VALUE';
  key: string;
  initialValue?: string;
}

// 处理属性对应值
export const propsMapValueFormat = (value: any) => {
  const typeString = Object.prototype.toString.call(value);
  const type = typeString.slice(8, -1);
  // 为对象
  switch (type) {
    case 'Object':
      return {
        ...value,
        itemType: 'VALUE',
      };
    default:
      return {
        itemDesc: value,
        itemType: 'VALUE',
        itemValue: value,
      };
  }
};

export interface Dict {
  name: string;
  code: string;

  [propsName: string]: any;
}

interface RuleConfigState {
  propsChoseOptions: Dict[];
  braceOptions: Dict[] | [];
  dataOperatorOptions: Dict[] | [];
  logicOperatorOptions: Dict[] | [];
  conditionList: Condition[] | [];
  propsCascaderOptions: any[];
  conditionListMap: any;
  [propsName: string]: any;
}

interface RuleConditionConfigProps {
  labelInstead?: string;
  modelCode?: string;
  value?: any;
  onChange?: any;
  editable?: any;
}

class RuleConditionConfig extends React.PureComponent<RuleConditionConfigProps, RuleConfigState> {
  constructor(props: any) {
    super(props)
  }
  state = {
    conditionList: [],
    conditionListMap: {},
    propsChoseOptions: [
      { name: '数据运算符', code: 'DATA_OPRTR' },
      { name: '括号', code: 'PARENTHESIS' },
      { name: '逻辑运算符', code: 'LOGCL_OPRTR' },
      { name: '字段', code: 'ATRBT_VALUE' },
    ],
    braceOptions: [],
    dataOperatorOptions: [],
    logicOperatorOptions: [],
    propsCascaderOptions: [
      // {
      //   key: 'test',
      //   label: '测试下拉',
      //   props: {
      //     inputValueComponentType: 'SELECT',
      //     "editable": true,
      //     "api": {
      //       "params": {
      //         "code": "YES_OR_NO"
      //       },
      //       "type": "GET",
      //       "url": "/sym/dict/findValues"
      //     },
      //   }
      // },
      // {
      //   key: '2',
      //   label: '测试日期',
      //   props: {
      //     inputValueComponentType: 'DATE_V1',
      //     editable: true,
      //   }
      // },
    ]
  };

  async componentDidMount() {
    const { value } = this.props;
    console.log('this.props', this.props);
    const res: any[] = await Promise.all([
      this.getDictValue('DATA_OPRTR'),
      this.getDictValue('PARENTHESIS'),
      this.getDictValue('LOGCL_OPRTR'),
    ]);

    if (res?.length < 1) return;
    DICT.map((key, index) => {
      const cData: ResponseType = res[index];
      return this.setState({
        [key]: cData.result,
      });
    });

    // 初始化属性选项
    if (this.props.modelCode) {
      const res: any = await this.getVoucherMeta(this.props.modelCode);

      if (res?.success) {
        this.setState({
          propsCascaderOptions: res.result?.pageDatas,
        });
      }
    }

    this.setConditionData(value);
  }

  async componentWillReceiveProps(nextProps: any, props: Readonly<RuleConditionConfigProps>) {
    const { value } = nextProps;
    if (nextProps.modelCode !== props.modelCode) {
      if (nextProps.modelCode) {
        const res: any = await this.getVoucherMeta(nextProps.modelCode);
        if (res?.success) {
          this.setState({
            propsCascaderOptions: res.result?.pageDatas,
          });
        }
      }
    }
    // 初始化数据
    this.setConditionData(value);
  }

  setConditionData = (value: any) => {
    const { conditionList } = this.state;

    if (value && JSON.stringify(value).includes('_1') && conditionList.length <= 0) {
      const opValue = _.cloneDeep(value);
      // 排序之后的数组
      const opConditionList: any[] = [];
      Object.keys(opValue).forEach(key => {
        const index: any = key.slice(-1);
        // @ts-ignore
        if (key.includes('ATRBT_VALUE')) {
          const objMap: any = {};
          const finalMap: any = {};
          opValue[key].forEach((o: any, indent: number) => {
            if (indent === 0) {
              objMap.cascaderValue = o.itemValue.split('.');
            }
            if (indent === 1) {
              objMap.dataOPValue = o.itemValue;
            }
            if (indent === 2) {
              objMap.cascaderMapValue = o.itemValue;
              // if (o.itemValue !== o.itemDesc) {
              objMap.cascaderMapValueProps = {
                itemDesc: o.itemDesc,
              };
              // }
            }
            finalMap.itemType = 'ATRBT_VALUE';
            finalMap.itemValue = objMap;
          });
          opConditionList[index - 1] = finalMap;
        } else {
          // 安总让改为数组
          opConditionList[index - 1] = {
            itemType: opValue[key][0].itemType,
            itemValue: opValue[key][0].itemValue,
          };
        }
      });
      const { conditionList: opArr, conditionListMap: opMap } = this.state;
      const conditionListOp = _.cloneDeep(opArr);
      const conditionListMap = _.cloneDeep(opMap);
      opConditionList.forEach(
        (row: { itemType: string; itemValue: string | undefined }, index: number) => {
          const uiKey = `${row.itemType}_${index + 1}`;
          conditionListMap[uiKey] = conditionListOp.length + 1;
          conditionListOp.push({
            // @ts-ignore
            key: uiKey,
            // @ts-ignore
            opKey: row.itemType,
            // @ts-ignore
            initialValue: row.itemValue,
          });
        },
      );
      this.setState({
        conditionList: [...conditionListOp],
        conditionListMap: { ...conditionListMap },
      });
    }
  }

  // 获取字典
  getDictValue = (code: string) =>
    xhrGet(api.dictValueList, {
      code,
    });

  // 获取凭证属性
  getVoucherMeta = (modelCode: string) =>
    modelCode && xhrGet(api.getMetaTree, {
      pageCode: modelCode,
    });

  getSelectOption = (arr: Dict[]) =>
    arr.map(o => (
      <Option key={o.code} value={o.code}>
        {o.name}
      </Option>
    ));

  // getCascaderOption = (arr: any[]) => arr;
  getCascaderOption = (arr: any[]) => arr.map(o => (
    <Option key={o.code} value={o.code}>
      {o.name}
    </Option>
  ));;

  // 添加条件组件
  addConditionComp = (key: 'DATA_OPRTR' | 'PARENTHESIS' | 'LOGCL_OPRTR' | 'ATRBT_VALUE') => {
    const { conditionList: opArr, conditionListMap: opMap } = this.state;
    const conditionList = _.cloneDeep(opArr);
    const conditionListMap = _.cloneDeep(opMap);
    const uiKey = `${key}_${conditionList.length + 1}`;
    conditionListMap[uiKey] = conditionList.length + 1;
    conditionList.push({
      // @ts-ignore
      key: uiKey,
      // @ts-ignore
      opKey: key,
    });
    this.setState({
      conditionListMap,
      conditionList: [...conditionList],
    });
  };

  // 删除条件组
  removeCondition = () => {
    const { conditionList: opArr, conditionListMap: opMap } = this.state;
    const { value, onChange }: any = this.props;
    const conditionList = _.cloneDeep(opArr);
    const conditionListMap = _.cloneDeep(opMap);
    if (conditionList?.length < 1) return;
    // 删除最后一条
    const delItem: Condition = conditionList[conditionList.length - 1];
    delete conditionListMap[delItem.key];
    if (value && value[delItem.key]) {
      delete value[delItem.key];
      // 触发form事件
      onChange(value);
    }
    conditionList.length -= 1;
    this.setState({
      conditionListMap,
      conditionList,
    });
  };

  // 获取条件组件对应options
  getConditionOptions = (key: 'DATA_OPRTR' | 'PARENTHESIS' | 'LOGCL_OPRTR' | 'ATRBT_VALUE') => {
    switch (key) {
      case 'DATA_OPRTR':
        return this.getSelectOption(this.state.dataOperatorOptions);
      case 'LOGCL_OPRTR':
        return this.getSelectOption(this.state.logicOperatorOptions);
      case 'PARENTHESIS':
        return this.getSelectOption(this.state.braceOptions);
      case 'ATRBT_VALUE':
        return this.getCascaderOption(this.state.propsCascaderOptions);
      default:
        return [];
    }
  };

  // 触发所有value更新
  handleTriggerChange = (e: any, data: any, key: any) => {
    // eslint-disable-next-line prefer-const
    let { onChange, value = {} }: any = this.props;
    if (!value || (Array.isArray(value) && value.length === 0)) {
      value = {};
    }
    if (e) {
      // 安总让改为数组
      value[key] = [{
        itemDesc: data.props.children,
        itemType: key.slice(0, -2),
        itemValue: data.props.value,
      }]
    } else {
      // 属性组件值处理
      value[key] = [
        {
          itemDesc: data.cascaderValue?.map((o: { label: any }) => o.label).join(','),
          itemType: key.slice(0, -2),
          itemValue: data.cascaderValue?.map((o: { key: any }) => o.key).join('.') || '',
        },
        {
          itemDesc: data?.dataOPValue?.children || data?.dataOPValue || '',
          itemType: 'DATA_OPRTR',
          itemValue: data?.dataOPValue?.value || data?.dataOPValue || '',
        },
        {
          ...propsMapValueFormat(data?.cascaderMapValue),
        },
      ];
    }
    console.log('changed', value);
    onChange(value);
  };

  // 
  getDetailValue = () => {
    const { conditionList } = this.state;
    const { value } = this.props;
    let dv = '';
    conditionList.forEach((item: any) => {
      value[item.key].forEach((i: any) => {
        dv += (` ${i.itemDesc} `)
      })
    })
    return dv
  }

  render() {
    const { propsChoseOptions, conditionList } = this.state;
    const { labelInstead, editable } = this.props;
    const formItemLayout = {
      labelCol: {
        span: 6
      },
      wrapperCol: {
        span: 18
      },
    };
    console.log('---->', editable, this.props, this.state)
    if (editable === false) {
      return <>
        {this.getDetailValue()}
      </>
    }
    return (
      <Row className="control-scroll-voucher" style={{ overflow: 'auto' }}>
        <Col span={8}>
          <Form.Item {...formItemLayout} label={getValidateMessage(labelInstead || 'bpmn.props', true)}>
            <SelectForm
              onChange={(e: any) => {
                this.addConditionComp(e);
              }}
              style={{ width: '50%' }}
            >
              {this.getSelectOption(propsChoseOptions)}
            </SelectForm>
            <ExtBtn
              style={{
                marginLeft: 10
              }}
              icon="shanchu"
              onClick={this.removeCondition}
              name={getValidateMessage('common.delete', true)}
            />
          </Form.Item>
        </Col>
        <Col span={23} style={{ marginTop: 6, overflow: 'auto' }}>
          {conditionList?.length > 0 && (
            <Row>
              <Col span={2}></Col>
              <Col style={{ display: 'flex', flexWrap: 'nowrap' }} span={22}>
                {conditionList.map((o: Condition) => {
                  const options: any = {};
                  if (o.initialValue) {
                    options.initialValue = o.initialValue;
                    options.value = o.initialValue;
                    // if (o.opKey === 'ATRBT_VALUE') {
                    //   options.initialValue = o.initialValue.split('.');
                    // }
                  }
                  return (
                    <Form.Item key={o.key} {...options}>
                      {
                        o.opKey === 'ATRBT_VALUE' ? (
                          <PropsComp
                            value={options?.value}
                            propsCascadeOptions={this.state.propsCascaderOptions || []}
                            dataOperatorOptions={this.getConditionOptions('DATA_OPRTR')}
                            onChange={(value: any) => this.handleTriggerChange(null, value, o.key)}
                          />
                        ) : (
                          <SelectForm
                            onChange={(e, row) => this.handleTriggerChange(e, row, o.key)}
                            defaultValue={options?.value}
                            style={{
                              width: '80px',
                              marginRight: 10,
                            }}
                          >
                            {this.getConditionOptions(o.opKey)}
                          </SelectForm>
                        )
                      }
                    </Form.Item>
                  );
                })}
              </Col>
            </Row>
          )}
        </Col>
      </Row>
    );
  }
}

export default RuleConditionConfig
